"""
验证器
"""
import json
import logging
import traceback
from typing import List, Dict
from datetime import datetime
from pydantic import BaseModel
from fastapi.encoders import jsonable_encoder

logger = logging.getLogger("crud")


def container_json_encode(item):
    logger.debug(f"[ActivityBase:container_json_encode] {item}-{type(item)}")
    if isinstance(item, List):
        try:

            for index, each in enumerate(item):
                if isinstance(each, BaseModel):
                    item[index] = each.dict()

            return json.dumps(item)
        except Exception:
            logger.debug("json序列化错误")
            logger.debug(traceback.format_exc())
            raise ValueError("img_path or related_items format error")
    elif isinstance(item, BaseModel):
        try:
            return item.json()
        except Exception:
            logger.debug("json序列化错误")
            logger.debug(traceback.format_exc())
            raise ValueError("img_path or related_items format error")

    else:
        raise TypeError("img_path or related_items is not a container, {}")


def container_json_decode(item):
    if isinstance(item, str):
        try:
            print("===========", item, type(item))
            return json.loads(item, strict=False)
        except Exception:
            logger.debug("json序列化错误")
            logger.debug(traceback.format_exc())
            raise ValueError("[container_json_decode:] img_path or related_items format error")

    else:
        raise TypeError("[container_json_decode:] img_path or related_items is not a container")


def datetime_str_decode(item):

    assert isinstance(item, datetime), f"{item} is not a type of datetime"
    return str(item)
